package elephant.rpc.network.netty.codec;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;

import elephant.rpc.server.RPCServer;
import elephant.rpc.server.core.PerformMonitor;
import elephant.rpc.server.message.RPCMessage;
import elephant.utils.DumpUtil;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import io.netty.handler.codec.CorruptedFrameException;

/**
 * 
 * @author skydu
 *
 */
public class FastJsonMessageDecoder extends ByteToMessageDecoder {
	//
	private static Logger logger=LoggerFactory.getLogger(FastJsonMessageDecoder.class);
	//
	PerformMonitor performMonitor;
	//
	public FastJsonMessageDecoder(PerformMonitor performMonitor){
		this.performMonitor=performMonitor;
	}
	/**
	 * 
	 */
	@Override
	protected void decode(ChannelHandlerContext ctx, ByteBuf in,
			List<Object> out) throws Exception {
		// Wait until the length prefix is available.
		if (in.readableBytes() < 4) {
			return;
		}
		in.markReaderIndex();
		int dataLength = in.readInt();
		if (dataLength > RPCServer.maxMsgLength) {
			in.resetReaderIndex();
			throw new CorruptedFrameException("message too long" + dataLength
					+ "/" + RPCServer.maxMsgLength);
		}
		if (in.readableBytes() < dataLength) {
			in.resetReaderIndex();
			return;
		}
		long startTime=System.currentTimeMillis();
		performMonitor.addTrafficIn(dataLength);
		byte[] decoded = new byte[dataLength];
		in.readBytes(decoded);
		RPCMessage msg;
		msg=JSON.parseObject(decoded,RPCMessage.class);
		out.add(msg);
		//
		long endTime=System.currentTimeMillis();
		if(logger.isDebugEnabled()){
			logger.debug("FastJsonMessageDecoder decode time:{} dataLength:{}\nmsg:{}",
					(endTime-startTime),
					dataLength,
					DumpUtil.dump(msg));
		}
	}
}
